package com.example.tests;


import java.util.concurrent.TimeUnit;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserManagementPage;
import com.example.pages.UserPage;
import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.esteru.selenium.factory.WebDriverFactory;

public class NewPass {
    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();
    private LoginPage loginPage;
    private UserPage newUserPage;
    private UserManagementPage newUserManagementPage;
    private WebDriverWait wait;

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://127.0.0.1/";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        wait = new WebDriverWait(driver,10);
    }

    @Test
    public void testNewPass() throws Exception {
        goToMainPage();
        loginAS("admin", "admin");
        ChangePass("admin");
        assertTrue("This is not users management page", newUserManagementPage.isOnManagementPage());
        LogOut();
    }

    private void ChangePass(String pass) {
        newUserPage.menuMyProfileLink.click();
        newUserPage.userPassword1.clear();
        newUserPage.userPassword1.sendKeys(pass);
        newUserPage.userPassword2.clear();
        newUserPage.userPassword2.sendKeys(pass);
        newUserPage.userSaveButton.click();
    }

    @After
    public void tearDown() throws Exception {
        //driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }
    private void LogOut() {
        newUserPage.menuLogoutLink.click();
        wait.until(alertIsPresent()).accept();
    }

    private void loginAS(String username, String password) {
        loginPage.userNameField.clear();
        loginPage.userNameField.sendKeys(username);
        loginPage.passwordField.clear();
        loginPage.passwordField.sendKeys(password);
        loginPage.loginButton.click();

    }

    private void goToMainPage() {
        // open main page
        driver.get(baseUrl + "/php4dvd/");
        loginPage = PageFactory.initElements(driver, LoginPage.class);
        newUserPage = PageFactory.initElements(driver, UserPage.class);
        newUserManagementPage = PageFactory.initElements(driver, UserManagementPage.class);
    }
}

